import os
import openpyxl
from robot.api import logger
import copy

AR3_EXPORT_XLSX = 'ar3_excel_path/ar3.xlsx'
AR3_EXPORT_XLS = 'ar3_excel_path/ar3.xls'
CURRENT_PATH = os.path.split(os.path.realpath(__file__))[0]

class ar3_open_excel(object):
    def __init__(self, path):
        self.path = path
        self.wb = None
        
    def __enter__(self):
        self.wb = openpyxl.load_workbook(self.path)
        return self.wb
    
    def __exit__(self, exc_type, exc_value, exc_tb):
        if self.wb:
            self.wb.save(self.path)
            self.wb.close()

def ar3_get_sheets(wb):
    return list(wb.get_sheet_names())

def ar3_open_sheet(wb, sheetname):
    return wb[sheetname]

def ar3_get_max_row(sheet):
    return sheet.max_row

def ar3_get_max_column(sheet):
    return sheet.max_column

def ar3_read_cell_by_index(sheet, row, column):
    return sheet.cell(column=column, row=row).value

def ar3_convert_dictkey_tolower(data):
    ret = dict()
    for i in data:
        ret[i.lower()] = data[i] if data[i] else []
    return ret

def ar3_check_writedata(data):
    temp = copy.deepcopy(data)
    
    #传递的数据必须是用excel的表头作为key，值是一个列表组成的数据
    if not isinstance(temp, dict):
        raise Exception(u'data数据必须是字典类型的')
    
    for k, v in temp.items():
        if v and not isinstance(v, list):
            logger.error('%s: %s' % (k, v))
            raise Exception(u'data里面的每个key对应的数据必须是列表类型的或者None')
        
    return ar3_convert_dictkey_tolower(temp)

def ar3_write_column_data(sheet, column_index, data):
    if not isinstance(data, list):
        raise Exception(u'data数据必须是列表类型的')
    for i, j in enumerate(data, 1):
        sheet.cell(column=column_index, row=i, value=j)

